package com.showboom.elauncher.receiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.showboom.elauncher.MyAppliacation;
import com.showboom.elauncher.activity.MainActivity;
import com.showboom.elauncher.activity.NoNetActivity;
import com.showboom.elauncher.activity.SimErrorDialog;
import com.showboom.elauncher.util.HttpUtils;
import com.showboom.elauncher.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class NetReceiver extends BroadcastReceiver {

    public static final int MESSAGE_CHECK_STATUS = 201;
    Handler mHandler = MyAppliacation.getHandler();
    private long networkChangeTime = 0;
    Context mContext;
    public static final String ACTION_SIM_STATUE_CHANGE = "android.intent.action.SIM_STATE_CHANGED";

    public NetReceiver() {
    }

    public NetReceiver(Handler handler) {
        Log.d("leihuiming", "NetReceiver constr handler = " + (handler == null));
        mHandler = handler;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (mContext == null) {
            mContext = context;
        }
        if(mHandler == null) mHandler = MyAppliacation.getHandler();
        String action = intent.getAction();
        Log.d("leihuiming", "action = " + action);
        int provison = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0);
        if (provison == 0) return;
        switch (action) {
            case ConnectivityManager.CONNECTIVITY_ACTION:
                long time = getTime();
                if (time != networkChangeTime) {
                    networkChangeTime = time;
                    getNetWorkConnectionType(context);
                }
                break;
            case ACTION_SIM_STATUE_CHANGE:
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                int state = tm.getSimState();
                switch(state) {
                    case TelephonyManager.SIM_STATE_ABSENT:
                        if(mHandler != null) {
                            mHandler.sendEmptyMessageDelayed(MainActivity.MSG_SIM_ABSENT, 30 * 1000);
                        }
                        break;
                    case TelephonyManager.SIM_STATE_READY:
                    case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                    case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                    case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                        if(mHandler != null && mHandler.hasMessages(MainActivity.MSG_SIM_ABSENT)) {
                            mHandler.removeMessages(MainActivity.MSG_SIM_ABSENT);
                        }
                        break;
                }
                break;
            default:
                break;
        }
    }

    public void getNetWorkConnectionType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            Log.d("leihuiming", "networkInfo type = " + networkInfo.getType());
            if (networkInfo.getType() != ConnectivityManager.TYPE_WIFI) {
                //startListenNet();
                if(mHandler != null) {
                    mHandler.sendEmptyMessage(MainActivity.MSG_SHOW_NONET_DIALOG);
                    MainActivity.updateWorkStatus(0);
                }
            } else {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(MainActivity.MSG_DISMISS_NONET_DIALOG);
                    //mHandler.sendEmptyMessage(MESSAGE_CHECK_STATUS);
                    if(!MainActivity.simStatus) {
                        //simCheckTast.execute();
                        mHandler.sendEmptyMessage(MainActivity.MSG_CHECK_SIM_STATUS);
                    }
                }
            }
        } else {
            //startListenNet();
            if(mHandler != null) {
                mHandler.sendEmptyMessage(MainActivity.MSG_SHOW_NONET_DIALOG);
                MainActivity.updateWorkStatus(0);
            }
        }
    }

    private void startListenNet() {
        Timer timer = new Timer();
        timer.schedule(netListener, 0, 60 * 1000);
    }

    int delayCount = 0;
    TimerTask netListener = new TimerTask() {
        @Override
        public void run() {
            delayCount++;
            Log.d("leihuiming", "delayCount = " + delayCount);
            if (delayCount <= 0) {
                if (Util.hasWifiConnection(mContext)) {
                    if(mHandler != null) {
                        netListener.cancel();
                        delayCount = 0;
                        //mHandler.sendEmptyMessage(MainActivity.MSG_DISMISS_NONET_DIALOG);
                    }
                }
            } else {
                //startNoNetActivity(mContext);
                if(mHandler != null) {
                    mHandler.sendEmptyMessage(MainActivity.MSG_SHOW_NONET_DIALOG);
                    MainActivity.updateWorkStatus(0);
                    netListener.cancel();
                    delayCount = 0;
                }
            }
        }
    };

    public void startNoNetActivity(Context context) {
        Intent intent = new Intent(context, NoNetActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public long getTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        String date = sDateFormat.format(new java.util.Date());
        return Long.valueOf(date);
    }

    public AsyncTask simCheckTast = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
            String currentICCID = Util.getIccid();
            Map<String, String> param = new HashMap<>();
            param.put("service", "getDeviceMobile");
            param.put("imei", Util.getImei(MyAppliacation.context));
            param.put("iccid", currentICCID);
            String result = HttpUtils.submitPostData(Util.base_url, param, "utf-8");
            return result;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String result = (String) o;
            if (!result.equals("-1") && !result.startsWith("err")) {
                try {
                    JSONObject object = new JSONObject(result);
                    int code = object.getInt("code");
                    if (code != 0) {
                        //dialog.show();
                        MainActivity.simStatus = false;
                        mHandler.sendEmptyMessage(MainActivity.MSG_SIM_ERROR);
                        Log.d("leihuiming", "SIM CARD ERROR!");
                    } else {
                        MainActivity.simStatus = true;
                        Log.d("leihuiming", "SIM CARD SUCCESS!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MainActivity.simStatus = false;;
                }
            } else {
                MainActivity.simStatus = false;
                mHandler.sendEmptyMessage(MainActivity.MSG_SIM_ERROR);
            }
        }
    };

}
